<template>
  <el-card shadow="never" class="search-form mb-md">
    <el-form 
      :model="modelValue" 
      @submit.prevent="handleSearch"
      :label-width="labelWidth"
      label-position="right"
      size="default"
    >
      <div class="form-content">
        <slot></slot>
      </div>
      
      <div class="search-form-buttons">
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, defineEmits, defineProps } from 'vue'

defineOptions({
  name: 'SearchForm'
})

const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  },
  labelWidth: {
    type: String,
    default: '80px'
  }
})

const emits = defineEmits(['update:modelValue', 'search', 'reset'])

// 重置表单
const handleReset = () => {
  // 创建一个新的对象，基于modelValue的类型，但所有属性设置为默认值
  const resetValue: Record<string, any> = {}
  
  for (const key in props.modelValue) {
    if (Array.isArray(props.modelValue[key])) {
      resetValue[key] = []
    } else if (typeof props.modelValue[key] === 'number') {
      resetValue[key] = undefined
    } else if (typeof props.modelValue[key] === 'boolean') {
      resetValue[key] = false
    } else {
      resetValue[key] = ''
    }
  }
  
  emits('update:modelValue', resetValue)
  emits('reset')
}

// 执行搜索
const handleSearch = () => {
  emits('search', props.modelValue)
}
</script>

<style scoped lang="scss">
.search-form {
  margin-bottom: 20px;
  
  .form-content {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    
    :deep(.el-form-item) {
      margin-bottom: 8px;
      min-width: 240px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .search-form-buttons {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
}

@media (max-width: 768px) {
  .search-form {
    .form-content {
      flex-direction: column;
      
      :deep(.el-form-item) {
        width: 100%;
      }
    }
  }
}
</style>
